package com.fsq.portscan.Utils;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.tools.Server;

public class DbUtils {

    static Server server;
    static JdbcConnectionPool cp;

    public static void startDB() {
        try {
            server = Server.createTcpServer("-webAllowOthers").start();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void stopDB() {
        server.stop();
    }

    public static void createConnectPool() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        String jarPath = JarUtils.getJarDir();
        System.out.println();
        String fileName = "jdbc:h2:" + jarPath + File.separator + sdf.format(d);
        System.out.println("db path:" + jarPath + ";\toutputfile:" + fileName);
        cp = JdbcConnectionPool.create(fileName, "sa", "sa");
    }

    public static Connection getConnection() {
        try {
            Connection conn = cp.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

    }

    public static void init() {
        startDB();
        createConnectPool();
    }

    public static void dispose() {
        cp.dispose();
    }

}
